package com.xian.im.modules.command.group.handler;

import com.xian.im.common.constant.CommandCodeConstant;
import com.xian.im.common.exception.BusinessException;
import com.xian.im.common.model.dto.GroupDto;
import com.xian.im.common.model.session.SessionUser;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.common.proto.MsgResponse;
import com.xian.im.common.utils.bussiness.XimResponseUtil;
import com.xian.im.common.utils.sys.SpringContextHolder;
import com.xian.im.modules.avchat.manager.ImGroupManager;
import com.xian.im.modules.command.group.AbsGroupCommand;
import com.xian.im.modules.message.GroupHandler;

import java.security.NoSuchAlgorithmException;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-01-28 22:32
 **/
public class GroupJoin extends AbsGroupCommand {

    @Override
    public void handler(MsgRequest request, String ctx, GroupDto groupEntity) throws NoSuchAlgorithmException {
        if (userChannelClient().hasGroup(request.getGroupUniqueId(), ctx)) {
            throw new BusinessException("已加入群组，无需再次加入");
        }
        userChannelClient().bindChannelGroup(groupEntity, ctx);
        groupManager().recordOnLine(groupEntity.getGroupUniqueId(),ctx);
        SessionUser sessionUser = userChannelClient().session(ctx);
        MsgResponse success = XimResponseUtil.buildSuccess(sessionUser);
        success.setGroupUniqueId(groupEntity.getGroupUniqueId());
        success.setBody(success.getUser().getNickname() + "加入了房间");
        GroupHandler.groupSendAll(success, groupEntity.getGroupUniqueId());
    }

    /**
     * 群组code
     *
     * @return
     */
    @Override
    public String cmdCode() {
        return CommandCodeConstant.GROUP_JOIN;
    }

    private static ImGroupManager groupManager(){
        return SpringContextHolder.getBean(ImGroupManager.class);
    }
}
